package com.lyhengtongwl.zqsnews.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;

import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.base.Constant;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.utils.BitmapCompressUtils;
import com.lyhengtongwl.zqsnews.utils.ImRezUtils;
import com.lyhengtongwl.zqsnews.utils.ImageRotationUtils;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.utils.TitleBuilder;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;
import com.makeramen.roundedimageview.RoundedImageView;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

import static com.lyhengtongwl.zqsnews.base.Constant.PICK_PHOTO_CODE;

public class NewsRecActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    private String photoName = "/faceImgNow.jpg";
    @BindView(R.id.iv_head)
    RoundedImageView iv_head;
    private Dialog dialog;
    private final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//存储权限
            Manifest.permission.READ_EXTERNAL_STORAGE};

    @OnClick({R.id.tv_share
    })
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        //调用相机拍照
        if (view.getId() == R.id.tv_share) {
            getPermission();
        }
    }

    /**
     * 获取相关权限
     */
    private void getPermission() {
        if (EasyPermissions.hasPermissions(this, PERMISSIONS)) {
            //已经打开权限
            File myhead = new File(Constant.DIR_INFO.APP_DIR + photoName);
            Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri uri = FileProvider.getUriForFile(NewsRecActivity.this,
                    getPackageName() + ".provider", myhead);
            it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(it, PICK_PHOTO_CODE);
        } else {
            //没有打开相关权限、申请权限
            EasyPermissions.requestPermissions(this, "需要获取您的相册、相机使用权限，否则将无法进行人脸识别！", 1, PERMISSIONS);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //回调结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (perms.size() == 3) {
            //已经打开权限
            File myhead = new File(Constant.DIR_INFO.APP_DIR + photoName);
            Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri uri = FileProvider.getUriForFile(NewsRecActivity.this,
                    getPackageName() + ".provider", myhead);
            it.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(it, PICK_PHOTO_CODE);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        NewsToastUtils.showToast(App.getContext(),"权限已被拒绝，请手动在设置里面打开权限！");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //拍照
        if (requestCode == PICK_PHOTO_CODE && resultCode == RESULT_OK) {
            try {
                String path = Constant.DIR_INFO.APP_DIR + photoName;
                Log.e("path", "onActivityResult: " + path);
                File temp = new File(path);
                if (temp.exists()) {
                    // TODO 上传服务器
                    //图片旋转操作
                    iv_head.setImageBitmap(ImageRotationUtils.getBitmap(path));
                    Bitmap bm = BitmapFactory.decodeFile(path);
                    bm = BitmapCompressUtils.imageZoom(bm, 50);
                    temp = ImRezUtils.saveBitmapFile(bm, path);
                    auth(temp);
                } else {
                    NewsToastUtils.showToast(NewsRecActivity.this, "文件不存在！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    //旋将旋转后的图片翻转

    //上传图片
    public void auth(File file) {
        dialog = new CenterDialog(R.layout.loading_layout, NewsRecActivity.this).showLoad("正在进行实名认证...");
        try {
            RequestBody requestFile =
                    RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part body =
                    MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            Task.getApiService().authImg(body).enqueue(new MyCallback<NewsBaseEntity>(NewsRecActivity.this) {
                @Override
                protected void onSuccess(Response<NewsBaseEntity> response) {
                    dialog.dismiss();
                    NewsToastUtils.showToast(NewsRecActivity.this, response.body().getMsg());
                    if ("1".equals(response.body().getCode())) {
                        SPUtils.put(App.getContext(), "authStatus", "2");
                    }
                    finish();
                }

                @Override
                protected void onFailure(Throwable t) {
                    dialog.dismiss();
                    NewsToastUtils.showToast(NewsRecActivity.this, "连接超时！");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            dialog.dismiss();
        }

    }

    @Override
    public void setListen() {

    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_rec;
    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }

    @Override
    public void initView() {
        new TitleBuilder(this).setTitleText("人脸识别")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    }

    @Override
    public void initData() {
    }
}
